﻿using IdentityModel;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Devonline.Identity.Admin.Controllers;

/// <summary>
/// 接口管理
/// </summary>
[Route("api/[controller]")]
[ApiController]
[SecurityHeaders]
[Authorize(Roles = GROUP_MAINTAINERS)]
public class ApisController : ControllerBase
{
    private readonly AdminSetting _appSetting;
    private readonly ConfigurationDbContext _dbContext;
    private readonly ILogger<ApisController> _logger;

    public ApisController(
        AdminSetting appSetting,
        ConfigurationDbContext dbContext,
        ILogger<ApisController> logger)
    {
        _appSetting = appSetting;
        _dbContext = dbContext;
        _logger = logger;
    }

    [HttpGet]
    public async Task<IActionResult> EnsureSeedIdentityData()
    {
        var json = System.IO.File.ReadAllText("identityServerData.json");
        if (string.IsNullOrWhiteSpace(json))
        {
            return BadRequest("identityServerData.json文件不存在");
        }

        IdentityServerData identityServerData = json.ToJsonObject<IdentityServerData>();
        foreach (var resource in identityServerData.IdentityResources)
        {
            var exits = await _dbContext.IdentityResources.AnyAsync(a => a.Name == resource.Name);
            if (exits)
            {
                continue;
            }

            await _dbContext.IdentityResources.AddAsync(resource.ToEntity());
        }

        foreach (var apiScope in identityServerData.ApiScopes)
        {
            var exits = await _dbContext.ApiScopes.AnyAsync(a => a.Name == apiScope.Name);
            if (exits)
            {
                continue;
            }

            await _dbContext.ApiScopes.AddAsync(apiScope.ToEntity());
        }

        foreach (var resource in identityServerData.ApiResources)
        {
            var exits = await _dbContext.ApiResources.AnyAsync(a => a.Name == resource.Name);
            if (exits)
            {
                continue;
            }

            foreach (var s in resource.ApiSecrets)
            {
                s.Value = s.Value.ToSha256();
            }

            await _dbContext.ApiResources.AddAsync(resource.ToEntity());
        }

        foreach (var client in identityServerData.Clients)
        {
            var exits = await _dbContext.Clients.AnyAsync(a => a.ClientId == client.ClientId);
            if (exits)
            {
                continue;
            }

            foreach (var secret in client.ClientSecrets)
            {
                secret.Value = secret.Value.ToSha256();
            }

            client.Claims = client.Claims
                .Select(c => new IdentityServer4.Models.ClientClaim(c.Type, c.Value))
                .ToList();

            await _dbContext.Clients.AddAsync(client.ToEntity());
        }

        await _dbContext.SaveChangesAsync();
        return Ok();
    }
}